﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using openxml.butter.controller;
using openxml.butter.definition;

using StudioLib;

using System.Net;
using System.IO;
using System.Xml.Linq;


namespace OpenXmlWebBetter
{
    //gestion des contenu de fichier
    public partial class file : PageWithData
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String hMethod = Request.HttpMethod.ToLower();
            String method = Request.Params["method"];

            if (!Page.IsPostBack)
            {
                StudioTrace.WriteLine(hMethod + " : " + method );
                if ("edit".Equals(method ))
                {
                    StudioTrace.WriteLine("on va éditer");
                    OXBEdit();
                    return;
                }

                if ("get".Equals(hMethod))
                {
                    Download();
                }

                if ("head".Equals(hMethod))
                {

                    Head();

                }

                if ("sync".Equals(method))
                {
                    StudioTrace.WriteLine("on va synchroniser");
                    Synchroniser();
                }

                if ("post".Equals(hMethod))
                {
                    StudioTrace.WriteLine("on va sauver");
                    Save();
                }

            }
        }

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
        //----------------------------------------------------------------------
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(Page_Load);

        }

        private void Synchroniser()
        {

            try
            {
                String code = Request.Params["code"];
                String url = Request.ApplicationPath + "/dav/" + code + ".docx";

                StudioTrace.WriteLine("Url à synchroniser = " + url);

                HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(url);
                req.Method = "get";
                
                HttpWebResponse response = (HttpWebResponse) req.GetResponse();
                Stream stream = response.GetResponseStream();

                long size = response.ContentLength;
                byte[] arrBytes = new byte[size] ;

                stream.Read(arrBytes, 0, (int)size);
                stream.Close();
                response.Close();

                StudioTrace.WriteLine("taille du flux :" + size);
                //si taille 0 sortir
                if (size == 0)
                {
                    StudioTrace.WriteLine("flux vide , abandon code =" + code);
                    Response.StatusCode = 500;
                    Response.Status = "Flux vide";
                    Response.End();
                    return;
                }

                //récupérer l'objet
                DocumentTemplate template = DataFactory.Instance.get<DocumentTemplate>(_db, code);

                //modfier le binaire
                template.BinaryContent = arrBytes;
                arrBytes = null;

                //sauver l'object
                DataFactory.Instance.updateDocumentTemplate(_db, template);

                Response.StatusCode = 200;

                Response.End();

            }
            catch (Exception e)
            {
                StudioTrace.WriteLine("pb de synchro " + e.Message);
                Response.Status = "pb de synchro :" +e.Message ;
                Response.StatusCode = 500;
            }

        }
        private void Save()
        {
            try
            {
                String code = Request.Params["code"];
                int count = Request.ContentLength;
                foreach( var header in Request.Headers )
                {
                    StudioTrace.WriteLine(header.ToString() + ":" + Request.Headers[header.ToString()]);
                }

                StudioTrace.WriteLine("taille du flux :" + count );
                //si taille 0 sortir
                if (count == 0)
                {
                    StudioTrace.WriteLine("flux vide , abandon code =" + code);
                    Response.StatusCode = 500;
                    Response.Status = "Flux vide";
                    Response.End();
                    return;
                }

                //récupérer l'objet
                DocumentTemplate template = DataFactory.Instance.get<DocumentTemplate>(_db, code);

                //lire le contenu du binaire                
                byte[] arrBytes = Request.BinaryRead(count);
                
                if (arrBytes.Length.Equals(0))
                {
                    StudioTrace.WriteLine("flux vide , abandon code =" + code);
                    Response.StatusCode = 500;
                    Response.Status = "Flux vide";
                    arrBytes = null;
                    Response.End();
                    return;
                }

                //modfier le binaire
                template.BinaryContent = arrBytes;
                arrBytes = null;

                //sauver l'object
                DataFactory.Instance.updateDocumentTemplate(_db, template);
                
                Response.StatusCode = 200;
                
                Response.End();


            }
            catch (Exception e)
            {
                StudioTrace.WriteLine("pb save:" + e.Message);
            }
        }

        private void Download()
        {

            try
            {
                String code = Request.Params["code"];

                DocumentTemplate template = DataFactory.Instance.get<DocumentTemplate>(_db, code);
                StudioTrace.WriteLine("template lu:" + template.Code);

                byte[] bytes = template.BinaryContent;
                StudioTrace.WriteLine("taille du binaire lu:" + bytes.Length);

                //préparer le contenu binaire pour gérér les macros
                WebTemplateFactory wtf = (WebTemplateFactory)Application["webtemplatefactory"];
                StudioTrace.WriteLine("wtf ok :" + ( wtf != null ));
                bytes = wtf.PrepareTemplate(template);
                StudioTrace.WriteLine("taille du binaire après prépare:" + bytes.Length);

                Response.StatusCode = 200;
                Response.ContentType = "application/msword";
                Response.AddHeader("Content-Length", "" + bytes.Length);
                Response.AddHeader("Content-Disposition", "attachment;filename=" + template.Code  +".docx" );
                Response.AddHeader("Server", "myServer");               
                Response.AddHeader("Expires", "" + DateTime.Now);
                Response.AddHeader("Last-Modified", "" + new DateTime());
                

                Response.BinaryWrite(bytes);
               
                bytes = null;
                template = null;
               

                Response.End();
                
            }
            catch (Exception e)
            {
                StudioTrace.WriteLine("pb download:" + e.Message);
            }

        }

        private void Head()
        {

            try
            {
                String code = Request.Params["code"];

                DocumentTemplate template = DataFactory.Instance.get<DocumentTemplate>(_db, code);

                byte[] bytes = template.BinaryContent;
                int size = bytes.Length;
                bytes = null;
                template = null;
                
                Response.AddHeader("Server", "myServer");
                Response.AddHeader("Content-Length", "" + size);
                Response.AddHeader("Content-Disposition", "attachment;filename=" + template.Code + ".docx");
                Response.ContentType = "application/msword";
                Response.AddHeader("Expires", "" + new DateTime().AddHours(1));
                Response.AddHeader("Last-Modified", "" + new DateTime() );              
                Response.StatusCode = 200;
                Response.End();
                
            }
            catch (Exception e)
            {
                StudioTrace.WriteLine("pb head:" + e.Message);
            }

        }

        //renvoie un flux xml .oxb, dédié à l'édition du modèle 
        private void OXBEdit()
        {
            String code = Request.Params["code"];

            DocumentTemplate template = DataFactory.Instance.get<DocumentTemplate>(_db, code);
            XDocument xdoc = new XDocument(new XElement("oxb"));
            XElement root = xdoc.Element("oxb" ) ;

            if (template == null)
            {
                root.Add(new XElement("error", "Le modèle '" + code + "' n'existe pas!"));
            }
            else
            {
                Uri uri = Request.Url;
                String server = uri.Scheme + "://" + uri.Host + ":" + uri.Port ;
                root.Add(new XElement("server", server ));
                root.Add(new XElement("code",  code ));
                root.Add(new XElement("description",  template.Description));
            }

            Response.ContentType = "stoockies/oxb";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + template.Code + ".oxb");
            String xml = xdoc.ToString();
            Response.Headers["Content-Length"] =""+  xml.Length;
            Response.Write(xml);
            Response.End();

        }
    }
}